<template>
    <div class="add-room-lease">
        <el-form :model="form" :rules="rules" ref="formRef" label-width="120px" label-position="right" size="medium">
            <!-- 基本信息 -->
            <h3 class="form-section-title">基本信息</h3>
            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="所属小区" prop="communityId">
                        <el-select v-model="form.communityId" placeholder="请选择小区" style="width: 100%;"
                            @change="handleCommunityChange" clearable filterable>
                            <el-option v-for="item in communityOptions" :key="item.communityId"
                                :label="item.communityName" :value="item.communityId" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="房号" prop="roomId">
                        <el-select v-model="form.roomId" placeholder="请选择房号" style="width: 100%;"
                            @change="handleRoomChange" :disabled="!form.communityId" clearable filterable>
                            <el-option v-for="item in roomOptions" :key="item.roomId" :label="item.roomNumber"
                                :value="item.roomId" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="面积(㎡)" prop="roomArea">
                        <el-input v-model="form.roomArea" disabled />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="朝向" prop="orientation">
                        <el-input v-model="form.orientation" disabled />
                    </el-form-item>
                </el-col>
            </el-row>

            <!-- 合同信息 -->
            <h3 class="form-section-title">合同信息</h3>
            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="合同编号" prop="contractNumber">
                        <el-input v-model="form.contractNumber" placeholder="请输入合同编号" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="租赁方" prop="leaseCompany">
                        <el-input v-model="form.leaseCompany" placeholder="请输入租赁方" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="租赁方联系人" prop="leaseName">
                        <el-input v-model="form.leaseName" placeholder="请输入租赁方联系人" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="联系电话" prop="leasePhone">
                        <el-input v-model="form.leasePhone" placeholder="请输入联系电话" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="租户" prop="tenantName">
                        <el-input v-model="form.tenantName" placeholder="请输入租户" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="租户电话" prop="tenantPhone">
                        <el-input v-model="form.tenantPhone" placeholder="请输入租户电话" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="法定代表" prop="legalRepresentative">
                        <el-input v-model="form.legalRepresentative" placeholder="请输入法定代表" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="收费面积(㎡)" prop="collectionArea">
                        <el-input v-model.number="form.collectionArea" placeholder="请输入收费面积" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="签订日期" prop="signingDate">
                        <el-date-picker v-model="form.signingDate" type="date" placeholder="请选择签订日期"
                            style="width: 100%;" value-format="yyyy-MM-dd" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="租期(月)" prop="leaseTerm">
                        <el-input-number v-model="form.leaseTerm" :min="1" :max="36" style="width: 100%;" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="起租日期" prop="startDate">
                        <el-date-picker v-model="form.startDate" type="date" placeholder="请选择起租日期" style="width: 100%;"
                            value-format="yyyy-MM-dd" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="停租日期" prop="stopDate">
                        <el-date-picker v-model="form.stopDate" type="date" placeholder="请选择停租日期" style="width: 100%;"
                            value-format="yyyy-MM-dd" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="租金方式" prop="depositId">
                        <el-select v-model="form.depositId" placeholder="请选择租金方式" style="width: 100%;"
                            @change="handleDepositChange">
                            <el-option v-for="item in depositOptions" :key="item.depositId" :label="item.depositName"
                                :value="item.depositId" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item label="押金说明" prop="depositDescription">
                        <el-input v-model="form.depositDescription" type="textarea" :rows="2" placeholder="请输入押金说明" />
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item label="备注" prop="remarks">
                        <el-input v-model="form.remarks" type="textarea" :rows="2" placeholder="请输入备注" />
                    </el-form-item>
                </el-col>
            </el-row>

            <!-- 操作按钮 -->
            <div class="form-actions">
                <el-button @click="handleCancel">取消</el-button>
                <el-button type="primary" @click="handleSubmit" :loading="submitting">保存</el-button>
            </div>
        </el-form>
    </div>
</template>

<script>
import request, { communityRequest } from '@/utils/request'

export default {
    name: 'AddRoomLease',
    data() {
        // 自定义验证规则
        const validatePhone = (rule, value, callback) => {
            if (!value) {
                return callback(new Error('请输入联系电话'))
            }
            if (!/^1[3-9]\d{9}$/.test(value)) {
                return callback(new Error('请输入正确的手机号码'))
            }
            callback()
        }

        const validateDate = (rule, value, callback) => {
            if (!value) {
                return callback(new Error('请选择日期'))
            }
            callback()
        }

        return {
            submitting: false,
            isEditMode: false,
            communityOptions: [],
            roomOptions: [],
            depositOptions: [],
            form: {
                communityId: '',
                roomId: '',
                roomArea: '',
                orientation: '',
                depositId: 1,
                contractNumber: '',
                leaseCompany: '',
                leaseName: '',
                leasePhone: '',
                tenantName: '',
                tenantPhone: '',
                legalRepresentative: '',
                collectionArea: '',
                signingDate: '',
                leaseTerm: 12,
                startDate: '',
                stopDate: '',
                depositDescription: '',
                remarks: ''
            },
            rules: {
                communityId: [
                    { required: true, message: '请选择小区', trigger: 'change' }
                ],
                roomId: [
                    { required: true, message: '请选择房号', trigger: 'change' }
                ],
                contractNumber: [
                    { required: true, message: '请输入合同编号', trigger: 'blur' }
                ],
                leaseCompany: [
                    { required: true, message: '请输入租赁方', trigger: 'blur' }
                ],
                leaseName: [
                    { required: true, message: '请输入租赁方联系人', trigger: 'blur' }
                ],
                leasePhone: [
                    { required: true, validator: validatePhone, trigger: 'blur' }
                ],
                tenantName: [
                    { required: true, message: '请输入租户', trigger: 'blur' }
                ],
                tenantPhone: [
                    { required: true, validator: validatePhone, trigger: 'blur' }
                ],
                legalRepresentative: [
                    { required: true, message: '请输入法定代表', trigger: 'blur' }
                ],
                collectionArea: [
                    { required: true, message: '请输入收费面积', trigger: 'blur' },
                    { type: 'number', message: '收费面积必须为数字', trigger: 'blur' }
                ],
                signingDate: [
                    { required: true, validator: validateDate, trigger: 'change' }
                ],
                leaseTerm: [
                    { required: true, message: '请输入租期', trigger: 'blur' },
                    { type: 'number', message: '租期必须为数字', trigger: 'blur' }
                ],
                startDate: [
                    { required: true, validator: validateDate, trigger: 'change' }
                ],
                stopDate: [
                    { required: true, validator: validateDate, trigger: 'change' }
                ],
                depositId: [
                    { required: true, message: '请选择租金方式', trigger: 'change' }
                ]
            }
        }
    },
    created() {
        this.initForm()
        this.fetchCommunities()
        this.fetchDepositOptions()
    },
    methods: {
        initForm() {
            const { action, id } = this.$route.query
            this.isEditMode = action === 'edit'

            if (this.isEditMode && id) {
                this.fetchContractDetail(id)
            }
        },

        async fetchContractDetail(id) {
            try {
                const res = await request.get(`/roomLease/getRoomLeaseDetail?id=${id}`)
                if (res.code === 200 && res.data) {
                    const detail = res.data
                    this.form = {
                        ...this.form,
                        ...detail,
                        communityId: detail.communityId || '',
                        roomId: detail.roomId || '',
                        roomArea: detail.roomArea || '',
                        orientation: detail.orientation || '',
                        depositId: detail.depositId || 1,
                        leaseTerm: detail.leaseTerm || 12
                    }

                    // 如果有小区ID，获取对应的房间
                    if (detail.communityId) {
                        this.fetchRooms(detail.communityId)
                    }
                }
            } catch (error) {
                console.error('获取合同详情失败:', error)
                this.$message.error('获取合同详情失败')
            }
        },

        async fetchCommunities() {
            try {
                const res = await communityRequest.get('/community/selcomm')
                this.communityOptions = res.data || []
            } catch (error) {
                console.error('获取小区列表失败:', error)
                this.$message.error('获取小区列表失败')
            }
        },

        async fetchRooms(communityId) {
            try {
                const res = await request.get(`/room/listByCommunity?communityId=${communityId}`)
                this.roomOptions = res.data || []
            } catch (error) {
                console.error('获取房间列表失败:', error)
                this.$message.error('获取房间列表失败')
            }
        },

        async fetchDepositOptions() {
            try {
                const res = await request.get('/deposit/getLeaseDeposit/12') // 默认获取12个月的租金方式
                this.depositOptions = res.data || []
            } catch (error) {
                console.error('获取租金方式失败:', error)
                this.$message.error('获取租金方式失败')
            }
        },

        handleCommunityChange(communityId) {
            this.form.roomId = ''
            this.form.roomArea = ''
            this.form.orientation = ''

            if (communityId) {
                this.fetchRooms(communityId)
            } else {
                this.roomOptions = []
            }
        },

        handleRoomChange(roomId) {
            if (roomId) {
                const selectedRoom = this.roomOptions.find(item => item.roomId === roomId)
                if (selectedRoom) {
                    this.form.roomArea = selectedRoom.roomArea
                    this.form.orientation = selectedRoom.orientation
                }
            } else {
                this.form.roomArea = ''
                this.form.orientation = ''
            }
        },

        handleDepositChange(depositId) {
            // 可以在这里处理租金方式变化逻辑
        },

        handleCancel() {
            this.$router.go(-1)
        },

        async handleSubmit() {
            try {
                const valid = await this.$refs.formRef.validate()
                if (!valid) return

                this.submitting = true

                // 准备提交数据
                const submitData = { ...this.form }

                // 调用API
                const apiUrl = this.isEditMode
                    ? `/roomLease/updateRoomLease`
                    : `/roomLease/addRoomLease`

                const res = await request.post(apiUrl, submitData)

                if (res.code === 200) {
                    this.$message.success(this.isEditMode ? '修改成功' : '添加成功')
                    this.$router.push({ name: 'HousingLease' })
                } else {
                    this.$message.error(res.message || '操作失败')
                }
            } catch (error) {
                console.error('操作失败:', error)
                this.$message.error('操作失败')
            } finally {
                this.submitting = false
            }
        }
    }
}
</script>

<style scoped>
.add-room-lease {
    padding: 20px;
}

.form-section-title {
    margin: 20px 0 15px;
    padding-bottom: 10px;
    border-bottom: 1px solid #eee;
    font-size: 16px;
    color: #409EFF;
}

.form-actions {
    margin-top: 30px;
    text-align: center;
}

.el-form-item {
    margin-bottom: 18px;
}

.el-row {
    margin-bottom: 10px;
}
</style>
